package cn.sc.allinpay.allfavour.business.cashier;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import cn.pai.common.utils.AmtUtils;
import cn.pai.mvp.callback.MpCallBack;
import cn.pai.mvp.intervenor.Intervenor;
import cn.pai.mvp.presenter.PaiPresenter;
import cn.sc.allinpay.allfavour.app.Constant;
import cn.sc.allinpay.allfavour.base.Utils.ListUtils;
import cn.sc.allinpay.allfavour.base.Utils.ListUtilsHook;
import cn.sc.allinpay.allfavour.business.cashiersell.CashierSellActivity;
import cn.sc.allinpay.allfavour.business.common.data.CouponsData;
import cn.sc.allinpay.allfavour.business.common.data.MemberData;
import cn.sc.allinpay.allfavour.business.common.data.OrderData;
import cn.sc.allinpay.allfavour.business.common.data.OrderResult;
import cn.sc.allinpay.allfavour.business.coupon.CouponActivity;
import cn.sc.allinpay.allfavour.business.ewallet.EWalletActivity;
import cn.sc.allinpay.allfavour.business.payment.PaymentActivity;

/**
 * 收银 presenter
 * author：pany
 * on 2017/12/1 11:27
 */
public class CashierPresenter extends PaiPresenter<CashierContract.View> implements CashierContract.Presenter {

    public static final int REQ_DISCOUNT = 0x01;//会员权益优惠
    public static final int REQ_COUPONS = 0x02;//卡券优惠
    public static final int REQ_EWALLET = 0x03;//电子钱包

    private CashierModel model = new CashierModel();
    private OrderData order;//订单对象

    @Override
    protected Intervenor createIntervenor() {
        return new Intervenor() {

            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                Bundle bundle = view.getBundle();
                String transAmt = bundle.getString(Constant.BundleKey.TRANS_AMT);
                order = new OrderData();
                order.setTransAmt(transAmt);//总金额
                order.setPaidAmt(transAmt);//待支付金额
            }

            @Override
            public void onActivityResult(int requestCode, int resultCode, Intent data) {
                if (requestCode == REQ_DISCOUNT || requestCode == REQ_COUPONS || requestCode == REQ_EWALLET) {
                    if (Activity.RESULT_OK == resultCode) {
                        Bundle bundle = data.getExtras();
                        if (bundle != null) {
                            if (requestCode == REQ_COUPONS) {//卡券返回
                                ArrayList<CouponsData> couponsDatas = bundle.getParcelableArrayList(Constant.BundleKey.COUPONS);//卡券
                                String discountAmt = bundle.getString(Constant.BundleKey.DISCOUNT_AMT);//卡券
                                String paidAmt = bundle.getString(Constant.BundleKey.PAID_AMT);//待支付
                                order.getMemberData().setCoupons(couponsDatas);
                                order.setDisCouponAmt(discountAmt);
                                order.setPaidAmt(paidAmt);
                                view.showCouponsAmt(AmtUtils.formatNegY(discountAmt));
                                view.showPaidAmt(AmtUtils.formatY(paidAmt));
                            } else if (requestCode == REQ_EWALLET) {//电子钱包返回
                                String discountAmt = bundle.getString(Constant.BundleKey.DISCOUNT_AMT);//电子钱包
                                String paidAmt = bundle.getString(Constant.BundleKey.PAID_AMT);//待支付
                                order.setDisEWalletAmt(discountAmt);
                                order.setPaidAmt(paidAmt);
                                view.showEWalletAmt(AmtUtils.formatNegY(discountAmt));
                                view.showPaidAmt(AmtUtils.formatY(paidAmt));
                            }
                        }
                    } else {
                        super.onActivityResult(requestCode, resultCode, data);
                    }

                } else {
                    // 扫码返回后,获取解析结果
                    IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
                    if (result != null) {
                        String code = result.getContents();
                        String mode = "1";//默认扫码获取 1扫码 2手动输入
                        if (TextUtils.isEmpty(code) && data != null) {
                            mode = "2";//手动输入
                            code = data.getStringExtra(Constant.BundleKey.SCAN_CODE);
                        }
                        if (!TextUtils.isEmpty(code)) {
                            reqQueryMember(code, mode);
                        } else {
                            view.toast("取消扫描");
                        }
                    } else {
                        super.onActivityResult(requestCode, resultCode, data);
                    }
                }
            }
        };
    }

    @Override
    public void start() {
        if (TextUtils.isEmpty(order.getTransAmt())) {
            view.toast("交易金额不能为空");
            view.finish();
            return;
        }
        view.showMemberVisible(View.GONE);
        view.showTransAmt(AmtUtils.formatY(order.getTransAmt()));
        view.showPaidAmt(AmtUtils.formatY(order.getPaidAmt()));
        view.showOilType();
    }

    @Override
    public void reqQueryMember(final String code, final String authType) {
        view.loading("查询会员...");
        model.reqQueryMember(order.getTransAmt(), view.getOilType(), code, authType, new MpCallBack<MemberData, String>() {
            @Override
            public void onSuccess(MemberData resp) {

//                String a= "{\"balance\":\"1000\",\"couponName\":\"券模版一\",\"desc\":\"仅作测试使用\",\"share\":{\"coupon\":\"0\",\"rights\":\"0\",\"out\":\"0\"},\"endTime\":\"16:13:03\",\"startTime\":\"16:13:03\",\"unit\":\"元\",\"couponCode\":\"8668083668000001201\",\"discountedAmt\":\"1000\",\"type\":\"0\",\"limit\":{\"reduceAmt\":\"1000\",\"specAmt\":\"0\",\"maxAmt\":\"1000\"}}";
//                CouponsData aa = JSON.parseObject(a,CouponsData.class);
//                resp.getCoupons().add(aa);

                final MemberData member = resp;
                member.setAuthCode(code.length() <= 32 ? code : code.substring(0, 32));//设置会员号码
                member.setAuthType(authType);//1会员动态码2手机号
                order.setMemberData(member);//设置会员信息

                view.showMemberLevel(member.getLevel());
                view.showMemberName(member.getMemberName());
                view.showMemberNo(member.getCardNo());

                if (member.getOilDiscountName() != null) {
                    view.showDiscountExist(member.getOilDiscountName());

                } else {
                    view.showDiscountExist("");
                    view.showDiscountAmt("0.00");

                }
                String discountAmt = member.getOilDiscountAmt().toString();//会员权益优惠
                BigDecimal paidAmount = new BigDecimal(order.getTransAmt()).subtract(member.getOilDiscountAmt());
                if (BigDecimal.ZERO.compareTo(paidAmount) >= 0) {//剩余金额为负数或0，直接至为0
                    paidAmount = BigDecimal.ZERO;
                } else {
                    if (member.getCoupons() != null && !member.getCoupons().isEmpty()) {
                        List<CouponsData> deductionCoupons = ListUtils.filter(member.getCoupons(), new ListUtilsHook<CouponsData>() {
                            @Override
                            public boolean filter(CouponsData couponsData) {
                                return couponsData.getType() == 1 && new BigDecimal(couponsData.getDiscountedAmt()).compareTo(BigDecimal.ZERO) != 0;
                            }
                        });
                        BigDecimal deductionCouponDiscountAmt = BigDecimal.ZERO;
                        if (deductionCoupons != null && !deductionCoupons.isEmpty()) {
                            Collections.sort(deductionCoupons, new Comparator<CouponsData>() {
                                @Override
                                public int compare(CouponsData o1, CouponsData o2) {
                                    return new BigDecimal(o1.getDiscountedAmt()).subtract(new BigDecimal(o2.getDiscountedAmt())).compareTo(BigDecimal.ZERO);
                                }
                            });
                            final BigDecimal finalPaidAmount = paidAmount;
                            List<CouponsData> fullDeductionCoupons = ListUtils.filter(deductionCoupons, new ListUtilsHook<CouponsData>() {
                                @Override
                                public boolean filter(CouponsData couponsData) {
                                    return BigDecimal.ZERO.compareTo(finalPaidAmount.subtract(new BigDecimal(AmtUtils.changeF2Y(couponsData.getDiscountedAmt())))) == 0;
                                }
                            });

                            int usedCouponIndex;

                            if (fullDeductionCoupons != null && fullDeductionCoupons.size() > 0) {
                                deductionCouponDiscountAmt = deductionCouponDiscountAmt.add(new BigDecimal(AmtUtils.changeF2Y(fullDeductionCoupons.get(0).getDiscountedAmt())));
                                usedCouponIndex = member.getCoupons().indexOf(fullDeductionCoupons.get(0));
                            } else {
                                deductionCouponDiscountAmt = deductionCouponDiscountAmt.add(new BigDecimal(AmtUtils.changeF2Y(deductionCoupons.get(deductionCoupons.size() - 1).getDiscountedAmt())));
                                usedCouponIndex = member.getCoupons().indexOf(deductionCoupons.get(deductionCoupons.size() - 1));
                            }

                            paidAmount = paidAmount.subtract(deductionCouponDiscountAmt);
                            if (BigDecimal.ZERO.compareTo(paidAmount) >= 0) {//剩余金额为负数，直接至为0
                                paidAmount = BigDecimal.ZERO;
                            }
                            member.getCoupons().get(usedCouponIndex).setUse(true);
                            member.getCoupons().get(usedCouponIndex).setUseNumber(1);
                        }

                        List<CouponsData> amountCoupons = ListUtils.filter(member.getCoupons(), new ListUtilsHook<CouponsData>() {
                            @Override
                            public boolean filter(CouponsData couponsData) {
                                return couponsData.getType() == 0 && new BigDecimal(couponsData.getBalance()).compareTo(BigDecimal.ZERO) != 0;
                            }
                        });

                        BigDecimal amountCouponDiscountAmt = BigDecimal.ZERO;

                        if (amountCoupons != null && !amountCoupons.isEmpty() && BigDecimal.ZERO.compareTo(paidAmount) < 0) {
                            Collections.sort(amountCoupons, new Comparator<CouponsData>() {
                                @Override
                                public int compare(CouponsData o1, CouponsData o2) {
                                    return new BigDecimal(o1.getBalance()).subtract(new BigDecimal(o2.getBalance())).compareTo(BigDecimal.ZERO);
                                }
                            });

                            for (CouponsData coupon : amountCoupons) {
                                List<CouponsData> usedCoupons = ListUtils.filter(member.getCoupons(), new ListUtilsHook<CouponsData>() {
                                    @Override
                                    public boolean filter(CouponsData couponsData) {
                                        return couponsData.isUse();
                                    }
                                });

                                if (usedCoupons != null && usedCoupons.size() == 9) {
                                    break;
                                }
                                amountCouponDiscountAmt = amountCouponDiscountAmt.add(new BigDecimal(AmtUtils.changeF2Y(coupon.getBalance())));
                                if ((paidAmount.subtract(amountCouponDiscountAmt)).compareTo(BigDecimal.ZERO) >= 0) {
                                    int usedIndex = member.getCoupons().indexOf(coupon);
                                    member.getCoupons().get(usedIndex).setUse(true);
                                    member.getCoupons().get(usedIndex).setUseAmt(AmtUtils.changeF2Y(member.getCoupons().get(usedIndex).getBalance()));
                                } else {
                                    amountCouponDiscountAmt = amountCouponDiscountAmt.subtract(new BigDecimal(AmtUtils.changeF2Y(coupon.getBalance())));
                                    BigDecimal usedAmt = paidAmount.subtract(amountCouponDiscountAmt);
                                    amountCouponDiscountAmt = amountCouponDiscountAmt.add(usedAmt);
                                    int usedIndex = member.getCoupons().indexOf(coupon);
                                    member.getCoupons().get(usedIndex).setUse(true);
                                    member.getCoupons().get(usedIndex).setUseAmt(usedAmt.toString());
                                }
                            }

                            if (BigDecimal.ZERO.compareTo(paidAmount.subtract(amountCouponDiscountAmt)) >= 0) {
                                amountCouponDiscountAmt = paidAmount;
                            }
                            paidAmount = paidAmount.subtract(amountCouponDiscountAmt);
                            if (BigDecimal.ZERO.compareTo(paidAmount) >= 0) {//剩余金额为负数，直接至为0
                                paidAmount = BigDecimal.ZERO;
                            }
                        }
                        order.getMemberData().setCoupons(member.getCoupons());
                        order.setDisCouponAmt(BigDecimal.ZERO.compareTo(deductionCouponDiscountAmt.add(amountCouponDiscountAmt)) != 0 ? (deductionCouponDiscountAmt.add(amountCouponDiscountAmt)).toString() : null);
                    }

                    if (!TextUtils.isEmpty(member.getBal()) && BigDecimal.ZERO.compareTo(paidAmount) < 0) {
                        BigDecimal disEWalletAmt = new BigDecimal(AmtUtils.changeF2Y(member.getBal()));
                        if (BigDecimal.ZERO.compareTo(paidAmount.subtract(disEWalletAmt)) >= 0) {
                            disEWalletAmt = paidAmount;
                        }
                        paidAmount = paidAmount.subtract(disEWalletAmt);
                        if (BigDecimal.ZERO.compareTo(paidAmount) >= 0) {//剩余金额为负数，直接至为0
                            paidAmount = BigDecimal.ZERO;
                        }
                        order.setDisEWalletAmt(BigDecimal.ZERO.compareTo(disEWalletAmt) != 0 ? disEWalletAmt.toString() : null);
                    }
                }
                String paidAmt = paidAmount.toString();//待支付
                order.getMemberData().setOilDiscountAmt(member.getOilDiscountAmt());
                order.getMemberData().setOilDiscountName(member.getOilDiscountName());
                order.setPaidAmt(paidAmt);//待支付金额
                view.showDiscountAmt(AmtUtils.formatNegY(discountAmt));
                view.showCouponsAmt(AmtUtils.formatNegY(order.getDisCouponAmt()));
                view.showEWalletAmt(AmtUtils.formatNegY(order.getDisEWalletAmt()));
                view.showPaidAmt(AmtUtils.formatY(paidAmt));
                view.showMemberVisible(View.VISIBLE);

                if (member.getCoupons() != null && !member.getCoupons().isEmpty()) {
                    view.showCouponsNumber(String.valueOf(member.getCoupons().size()));
                } else {
                    view.showCouponsNumber("0");
                }
                view.showEWalletBal(!TextUtils.isEmpty(member.getBal()) ? AmtUtils.changeF2Y(member.getBal()) : "0.00");
                view.loaded();
            }

            @Override
            public void onFailure(String response, String message) {
                view.loaded();
                view.prompt(message);
            }
        });
    }

    @Override
    public void startCouponsActivity() {
        List<CouponsData> coupons = order.getMemberData().getCoupons();
        if (coupons == null || coupons.isEmpty()) {
            view.toast("无优惠卡券");
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putParcelable(Constant.BundleKey.PAY_ORDER, order);
        view.toActivityForResult(CouponActivity.class, bundle, REQ_COUPONS);
    }

    @Override
    public void startEWalletActivity() {
        String bal = order.getMemberData().getBal();
        if (TextUtils.isEmpty(bal) || BigDecimal.ZERO.compareTo(new BigDecimal(bal)) == 0) {
            view.toast("无电子钱包");
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putParcelable(Constant.BundleKey.PAY_ORDER, order);
        view.toActivityForResult(EWalletActivity.class, bundle, REQ_EWALLET);
    }

    @Override
    public void startPay() {
        order.setCashierNo(model.getGlobal().getCashierData().getCashierNo());
        order.setCashierName(model.getGlobal().getCashierData().getCashierName());
        order.setGuideId(view.getGuideID());
        order.setGuideName(view.getGuideName());
        order.setOilType(view.getOilType());
        order.setOilName(view.getOilName());

        if (isReqSellOrder()) {
            Bundle bundle = new Bundle();
            bundle.putParcelable(Constant.BundleKey.PAY_ORDER, order);
            view.toActivity(CashierSellActivity.class, bundle);
        } else {
            view.loading("订单创建中...");

            model.reqSellOrder(order.getMemberData() != null ? order.getMemberData().getAuthCode() : null, order.getTransAmt(), null, null, null, order.getMemberData() != null && order.getMemberData().getOilDiscountAmt() != null ? order.getMemberData().getOilDiscountAmt().toString() : null, order.getPaidAmt(), order.getOilType(), new MpCallBack<OrderResult, String>() {
                @Override
                public void onSuccess(OrderResult orderResult) {
                    if (view == null) {
                        return;
                    }
                    order.setOrderId(orderResult.getOrderNo());
                    order.setRetTime(orderResult.getRetTime());
                    view.loaded();
                    Bundle bundle = new Bundle();
                    bundle.putParcelable(Constant.BundleKey.PAY_ORDER, order);
                    view.toActivity(PaymentActivity.class, bundle);
                    view.finish();
                }

                @Override
                public void onFailure(String response, String message) {
                    if (view == null) {
                        return;
                    }
                    view.loaded();
                    view.prompt(message);
                }
            });
        }
    }

    /**
     * 是否发起订单销账
     */
    private boolean isReqSellOrder() {
        if (!TextUtils.isEmpty(order.getDisCouponAmt()) || //卡券折扣不为空
                !TextUtils.isEmpty(order.getDisEWalletAmt())) {//电子钱包不为空
            return true;
        }
        return false;
    }
}
